#include <stdio.h>
#include <errno.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>

int main() {
    int sockfd;
    struct sockaddr_in servaddr, localaddr;
    socklen_t len;
    char straddr[16];

    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0) ) < 0) {
        perror("socket");
        return -1;
    }

    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(9999);

    if ( bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
        perror("bind");
        return -1;
    }
    if(getsockname(sockfd, (struct sockaddr *)&localaddr, &len) < 0 ){
        perror("getsockname");
        return -1;
    }
    // 打印出地址和端口
    inet_ntop(AF_INET, &localaddr.sin_addr.s_addr, straddr, 16);
    printf("bind ip:%s port:%d\n", straddr, ntohs(localaddr.sin_port));

    return 0;
}